<template>
  <div class="mobile-home">
    <!-- 顶部搜索栏 -->
    <div class="mobile-search-bar">
      <div class="logo">
        <img
          src="@/assets/6989d94d0c54ab6b8bcce0fd6f845ed.png"
          width="40px"
          height="40px"
          alt="影厅票务网Logo"
        />
        <span>影厅票务</span>
      </div>
      <div class="search-input">
        <el-input
          v-model="search"
          placeholder="搜索电影"
          size="small"
          :prefix-icon="Search"
          clearable
          @keyup.enter="searchFilm"
        />
      </div>
    </div>

    <!-- 轮播图区域 -->
    <div class="mobile-banner">
      <el-carousel :interval="3000" height="200px" indicator-position="none">
        <el-carousel-item
          v-for="item in bannerList"
          :key="item.id"
          @click="goToDetail(item.id)"
        >
          <img :src="item.photo" alt="电影海报" class="banner-image" />
          <div class="banner-title">{{ item.name }}</div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 分类标签 -->
    <div class="mobile-category">
      <div class="category-title">电影分类</div>
      <div class="category-tags">
        <el-tag
          v-for="(tag, index) in movieTags"
          :key="index"
          :class="{ 'active-tag': activeTag === index }"
          @click="filterByTag(index)"
          size="small"
        >
          {{ tag }}
        </el-tag>
      </div>
    </div>

    <!-- 电影列表 -->
    <div class="mobile-movie-list">
      <div class="list-title">正在热映</div>
      <div class="movie-grid">
        <div
          v-for="item in movieList"
          :key="item.id"
          class="movie-item"
          @click="goToDetail(item.id)"
        >
          <div class="movie-poster">
            <img :src="item.photo" alt="电影海报" class="poster-image" />
            <div class="movie-score">{{ item.rating }}分</div>
          </div>
          <div class="movie-info">
            <div class="movie-name">{{ item.name }}</div>
            <div class="movie-director">导演: {{ item.director }}</div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="loading-more" v-if="loading">
        <el-skeleton :rows="1" animated />
      </div>
      <div class="no-more" v-if="noMore">
        <span>没有更多数据了</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  mobileReqAllFilm,
  mobileReqBanner,
  mobileReqFilmByType,
} from '@/api/mobile'
import qs from 'qs'

const router = useRouter()

// 搜索
const search = ref('')
const searchFilm = () => {
  if (!search.value.trim()) {
    ElMessage.warning('请输入电影名称')
    return
  }
  currentPage.value = 1
  movieList.value = []
  noMore.value = false
  
  loadMovies({
    name: search.value.trim(),
    pageSize: pageSize.value,
    page: 1,
  })
}

// 轮播图数据
const bannerList = ref([])
const loadBanners = async () => {
  try {
    const result = await mobileReqBanner()
    if (result.code === 200) {
      bannerList.value = result.data
    }
  } catch (error) {
    console.error('加载轮播图失败', error)
  }
}

// 电影分类
const movieTags = ['全部', '动作', '喜剧', '爱情', '科幻', '恐怖', '动画']
const activeTag = ref(0)
const filterByTag = (index: number) => {
  activeTag.value = index
  currentPage.value = 1
  movieList.value = []
  noMore.value = false
  
  if (index === 0) {
    loadMovies({
      pageSize: pageSize.value,
      page: 1,
    })
  } else {
    loadMoviesByType({
      type: movieTags[index],
      pageSize: pageSize.value,
      page: 1,
    })
  }
}

// 电影列表数据
const movieList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const noMore = ref(false)

const loadMovies = async (params: any) => {
  try {
    loading.value = true
    // 使用qs.stringify转换参数
    const result = await mobileReqAllFilm(qs.stringify(params))
    if (result.code === 1) {
      if (params.page === 1) {
        movieList.value = result.data.records
      } else {
        movieList.value = [...movieList.value, ...result.data.records]
      }
      total.value = result.data.total
      noMore.value = movieList.value.length >= total.value
    }
  } catch (error) {
    console.error('加载电影列表失败', error)
  } finally {
    loading.value = false
  }
}

const loadMoviesByType = async (params: any) => {
  try {
    loading.value = true
    // 使用qs.stringify转换参数
    const result = await mobileReqFilmByType(qs.stringify(params))
    if (result.code === 200) {
      if (params.page === 1) {
        movieList.value = result.data.records
      } else {
        movieList.value = [...movieList.value, ...result.data.records]
      }
      total.value = result.data.total
      noMore.value = movieList.value.length >= total.value
    }
  } catch (error) {
    console.error('加载分类电影失败', error)
  } finally {
    loading.value = false
  }
}

// 加载更多数据
const loadMore = () => {
  if (loading.value || noMore.value) return
  
  currentPage.value++
  if (activeTag.value === 0) {
    loadMovies({
      pageSize: pageSize.value,
      page: currentPage.value,
      name: search.value.trim() || undefined,
    })
  } else {
    loadMoviesByType({
      type: movieTags[activeTag.value],
      pageSize: pageSize.value,
      page: currentPage.value,
    })
  }
}
let container: HTMLElement | null = null
// 优化后的滚动事件处理
const handleScroll = () => {
  console.log('正在滚动')  // 测试
  if (loading.value || noMore.value) return

  if (!container) return
  
  const scrollTop = container.scrollTop
  const clientHeight = container.clientHeight
  const scrollHeight = container.scrollHeight
  
  if (scrollHeight - (scrollTop + clientHeight) < 300) {
    loadMore()
  }
}

// 添加防抖处理
const debounceScroll = debounce(handleScroll, 200)

onMounted(() => {
  loadBanners()
  loadMovies({
    pageSize: pageSize.value,
    page: 1,
  })
  
  container = document.querySelector('.mobile-home')
  container?.addEventListener('scroll', debounceScroll)
})

onUnmounted(() => {
  container?.removeEventListener('scroll', debounceScroll)
})

// 简单的防抖函数实现
function debounce(fn: Function, delay: number) {
  let timer: ReturnType<typeof setTimeout> | null = null
  return function(...args: any[]) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

// 跳转到详情页
const goToDetail = (id: number) => {
  router.push(`/mobile/detail/${id}`)
}
</script>

<style scoped lang="scss">
.mobile-home {
  padding: 0 0 60px;
  height: 100vh;
  overflow-y: auto;
}

.mobile-search-bar {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;

  .logo {
    display: flex;
    align-items: center;
    margin-right: 10px;

    span {
      font-size: 16px;
      font-weight: bold;
      margin-left: 5px;
      color: #ff6b6b;
    }
  }

  .search-input {
    flex: 1;
  }
}

.mobile-banner {
  margin: 10px 0;

  .banner-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
  }

  .banner-title {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
    color: #fff;
    font-size: 16px;
    font-weight: bold;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
  }
}

.mobile-category {
  padding: 0 15px 15px;

  .category-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .category-tags {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    padding-bottom: 5px;

    &::-webkit-scrollbar {
      display: none;
    }

    .el-tag {
      margin-right: 8px;
      cursor: pointer;
      flex-shrink: 0;

      &.active-tag {
        background-color: #ff6b6b;
        color: #fff;
        border-color: #ff6b6b;
      }
    }
  }
}

.mobile-movie-list {
  padding: 0 15px;

  .list-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
  }

  .movie-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .movie-item {
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  .movie-poster {
    position: relative;
    height: 0;
    padding-bottom: 140%;

    .poster-image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .movie-score {
      position: absolute;
      top: 5px;
      right: 5px;
      background-color: rgba(255, 107, 107, 0.9);
      color: #fff;
      padding: 2px 6px;
      border-radius: 10px;
      font-size: 12px;
      font-weight: bold;
    }
  }

  .movie-info {
    padding: 8px;

    .movie-name {
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .movie-director {
      font-size: 12px;
      color: #909399;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.mobile-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
